<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Request;
use think\facade\Config;//引入配置
use TCPDF;
use Elasticsearch\ClientBuilder;

class Esapi extends Base
{

    /*发送参数页面*/
    public function send_data(){
        $data['seo_title']="es | Lily Bearing";
        $data['seo_keywords']="es | Lily Bearing";
        $data['seo_desc']="";
        $data['base_data']=$this->base_data;

        $this->assign($data);
        return $this->fetch();
    }

    /*符号替换*/
    public function replace_fh($str){
        $fh=array(' mm');
        $fhf=array('mm');
        $return_str=$str;
        foreach ($fh as $key => $value) {
            if(strpos($return_str,$value) !== false){ 
               $return_str=str_replace($value,trim($value),$return_str);
            }else{
              $return_str=$return_str;
            }
        }

        foreach ($fhf as $key => $value) {
            if(strpos($return_str,$value) !== false){ 
               $return_str=str_replace($value," ".trim($value),$return_str);
            }else{
              $return_str=$return_str;
            }
        }
        return $return_str;
    }

    public function appact_search(Request $request){
        $data['base_data']=$this->base_data;
        $get=request()->get();
        $default_lang=config('app.default_lang');
        if($default_lang=='en-us'){
            if (preg_match("/[\x7f-\xff]/", $get['q'])) { 
                $data['ci']=$get['q'];
                $data['seo_title']="No results for ".$get['q']." | Lily Bearing";
                $data['seo_keywords']="No results for ".$get['q'].", Lily Bearing";
                $data['seo_desc']="No results for ".$get['q']." | Lily Bearing";
                $this->assign($data);
                return $this->fetch('zhong');
            }
        }
        
        /*第一个和最后一个字符都是”时候去掉*/
        $first_str=mb_substr($get['q'], 0, 1);
        $end_str=mb_substr($get['q'], -1);
        if($first_str=='"'&&$end_str=='"'){
           $get['q']=trim($get['q'],'"');
        }
        $jump_brand_url=Db::table('lily_es_brand_url')->where('name','=',$get['q'])->find();
        if(!empty($jump_brand_url)){
            Header("Location: ".$jump_brand_url['url']);
            exit;
        }


        /*若输入和分类名一致直接跳转到分类的url*/
        $jump_url=Db::table('lily_classify')->field('id,cname,alias_name')->order('id')->select();
        foreach ($jump_url as $key => $value) {
            similar_text(strtolower($get['q']),lang(strtolower($value['cname'])),$percent1);
            if($percent1>=94){
               /* $class_uplower_data=class_uplower($value['id']);
                if(end($class_uplower_data)['id']==1&&$class_uplower_data[1]['id']!=1282){
                    Header("Location: //".Config::get('app.web_host_name')."/".get_class_uplower_url($value['id']));
                }*/

                Header("Location: //".Config::get('app.web_host_name')."/".get_class_uplower_url($value['id']));
                
            }
            
        }
        
        /*替换用户输入5mm为5 mm*/
        $sear=$this->replace_fh(strtolower($get['q']));

        if($default_lang=='en-us'){
            $data['seo_title']='Showing results for '.$sear.' | Lily Bearing';
            $data['seo_keywords']=$sear;
            $data['seo_desc']="Lily bearing is bearing manufacture and supplier from china.We supply ".$sear." bearing with any size and great price. Our bearing could be used including but not limited in medical, automotive, food and other industries. Also a formed pre-sales/sales/after-sales program system were used to meet the actual needs.";
        }else{
            $data['seo_title']='显示结果'.$sear.' | 养贞轴承';
            $data['seo_keywords']=$sear;
            $data['seo_desc']="养贞轴承是中国的轴承制造商和供应商。我们提供".$sear."轴承，尺寸和价格均可。我们的轴承可用于包括但不限于医疗、汽车、食品和其他行业。此外，还使用了一套完善的售前/销售/售后计划系统来满足实际需求。";
        }
        
        $data['appect']=$this->appact_search_result($sear,$get,'weidu');
        //dump($data['appect']);exit;
        if(empty($data['appect']['part_number_sear'])){
            $sear_null=preg_replace('/[^0-9a-zA-Z]+/i','',$sear);
            $data_sear_null=$this->appact_search_result($sear_null,$get,'weidu');
            if(empty($data_sear_null['part_number_sear'])){
                $data_sear_most=$this->appact_search_result($sear,$get,'most_fields');
                if(empty($data_sear_most['class_search'])&&empty($data_sear_most['weidu_search']['content_data3'])&&empty($data_sear_most['maxclass'])&&empty($data_sear_most['part_number_sear'])){

                    $no_way_search=$this->appact_search_result($sear,$get,'no_way_search');

                    if(empty($no_way_search['class_search'])&&empty($no_way_search['weidu_search'])&&empty($no_way_search['no_way_search']['bao_data'])&&empty($no_way_search['no_way_search']['recommend_data'])&&empty($no_way_search['part_number_sear'])){

                        $day=date("Y-m-d",time());
                        $dang=Db::connect('publicdata')->table('lily_searchcount')->where([['shu','=',$get['q']],['create_time','like','%'.$day.'%'],['ip','=',$this->base_data['ip']]])->select();
                        
                        if(empty($dang)&&$this->base_data['ip']!='222.64.21.2'){
                            $nodata=array();
                            $nodata['noresult']=$sear;
                            $nodata['shu']=$sear;
                            $nodata['create_time']=date('Y-m-d h:i:s',time());
                            $nodata['ip']=$this->base_data['ip'];
                            $nodata['sys']=$_SERVER['HTTP_USER_AGENT'];
                            $shibieip="https://apis.map.qq.com/ws/location/v1/ip?ip=".$this->base_data['ip']."&key=O4DBZ-LI26I-BEPGW-56A6T-FJNLZ-F4BWP";
                            $loaction=json_decode(file_get_contents($shibieip),true);
                            if($loaction['status']==0){
                               $country=$loaction['result']['ad_info']['nation'];
                            }else{
                               $country="未能识别";
                            }
                            $nodata['country']=$country;
                            if($country!='缅甸'){ 
                                Db::connect('publicdata')->table('lily_searchcount')->insert($nodata);
                            }

                        }
                    }else{
                       $data['appect']=$no_way_search; 
                    }
                }else{
                    $data['appect']=$data_sear_most;
                }
            }else{
                $data['appect']=$data_sear_null;
            }
        }
        
        $this->assign($data);
        $isMobile=isMobile();
        if($isMobile==1){
            return $this->fetch('appact_search_phone');
        }else{
            return $this->fetch('appact_search');
        }
    }

    public function appact_search_result($sear,$get,$type){
        $default_lang=config('app.default_lang');

        $Esadmin = controller('index/Esadmin');
        if($type=='weidu'){
            $part_number_search=$Esadmin->part_number_search($sear);
            $tuijian_part_number_search=$Esadmin->tuijian_part_number_search($sear,10);
            $class_search=$Esadmin->class_search($sear);
            $weidu_search=$Esadmin->weidu_search($sear);
            $data['class_search']=$class_search;
            $data['weidu_search']=$weidu_search;
            $part_number_sear=array_merge($part_number_search,$class_search,$weidu_search);
        }

        if($type=='most_fields'){
            $part_number_search=null;
            $tuijian_part_number_search=$Esadmin->tuijian_part_number_search($sear,10);
            $class_search=null;
            $weidu_search=$Esadmin->most_fields($sear);
            $data['class_search']=null;
            $data['weidu_search']=$weidu_search;
            $part_number_sear=array_merge($weidu_search);
        }

        if($type=='no_way_search'){
            $part_number_search=null;
            $tuijian_part_number_search=null;
            $class_search=null;
            $weidu_search=null;
            $no_way_search=$Esadmin->no_way_search($sear);
            $data['class_search']=null;
            $data['weidu_search']=null;
            $data['no_way_search']=$no_way_search;
            $part_number_sear=array_merge($no_way_search);
        }
        $zonghe=array();
        $return_data=array();
        $maxclass=array();

        $shai_return=array();
        $gets=array();
        $duibi_str='';

         if(count($get)>1){
            foreach ($get as $key => $value) {
                if($key!='q'&&$key!='tag'){
                  $gets[strtolower(str_replace('_','',$key))]=strtolower($value);
                  $duibi_str.=strtolower(str_replace('_','',$key)).strtolower($value);
                }
            }
        }
        
        foreach ($part_number_sear as $key => $value) {
            if(!empty($value)){

                foreach ($value as $key1 => $value1) {

                    if($default_lang=='en-us'){
                        $content=$value1['_source']['Content'];
                    }else{
                        $content=$value1['_source']['Content_zh'];
                    }

                    if(!in_array($value1['_source']['Part_Number'],$zonghe)){
                        $zonghe[]=$value1['_source']['Part_Number'];
                        if(!empty($class_search['class_data'])||!empty($weidu_search['content_data'])||!empty($weidu_search['content_data2'])){
                            if(isset($value1['_source']['maxclass'])){
                                
                                if(isset($get['tag'])&&!empty($get['tag'])){
                                    $maxclass_cname=json_decode(base64_decode($value1['_source']['maxclass']),true)['cname'];
                                    if(strtolower($get['tag'])==strtolower($maxclass_cname)){
                                        if(count($get)>1){
                                            $duibi='';
                                            foreach ($gets as $k => $v) {
                                                if(isset($content[$k])&&$v==strtolower(trim(explode(' || ',$content[$k])[1]))){
                                                    $duibi.=$k.strtolower($v);
                                                }
                                            }
                                            if($duibi==$duibi_str){
                                                $return_data[]=$value1['_source'];
                                            }
                                        }else{
                                            $return_data[]=$value1['_source'];
                                        }
                                    }
                                }else{
                                    $first = current(array_filter($part_number_sear))[0];
                                    $maxclass_cname=json_decode(base64_decode($first['_source']['maxclass']),true)['cname'];
                                    $maxclass_cname1=json_decode(base64_decode($value1['_source']['maxclass']),true)['cname'];
                                    if($maxclass_cname==$maxclass_cname1){
                                        if(count($get)>1){
                                            $duibi='';
                                            foreach ($gets as $k => $v) {
                                                if(isset($content[$k])&&$v==strtolower(trim(explode(' || ',$content[$k])[1]))){
                                                    $duibi.=$k.strtolower($v);
                                                }
                                            }
                                            if($duibi==$duibi_str){
                                                $return_data[]=$value1['_source'];
                                            }
                                        }else{
                                            $return_data[]=$value1['_source'];
                                        }
                                    }
                                }
                                
                            }
                           
                        }else{
                            if(count($get)>1){
                                $duibi='';
                                foreach ($gets as $k => $v) {
                                    if(isset($content[$k])&&$v==strtolower(trim(explode(' || ',$content[$k])[1]))){
                                        $duibi.=$k.strtolower($v);
                                    }
                                }
                                if($duibi==$duibi_str){
                                    $return_data[]=$value1['_source'];
                                }
                            }else{
                                $return_data[]=$value1['_source'];
                            }
                        }
                    }
                    if(!empty($class_search['class_data'])||!empty($weidu_search['content_data'])||!empty($weidu_search['content_data2'])){
                        if(!in_array($value1['_source']['maxclass'],$maxclass)){
                            $maxclass[]=$value1['_source']['maxclass'];
                        }
                    }
                }
            }
        }
        
        $data['maxclass']=$maxclass;
        $data['part_number_sear']=$return_data;
        
        
        /*所有左侧维度的名称*/
        $sear_left=array();
        
        foreach ($return_data as $key => $value) {
            if($default_lang=='en-us'){
                $content=$value['Content'];
            }else{
                $content=$value['Content_zh'];
            }
            foreach ($content as $k => $v) {
                $wi=explode(' || ',$v);
                $field=str_replace(' ','_',trim($wi[0]));
                $zhi=trim($wi[1]);
                if(!isset($sear_left[$field])){
                    $sear_left[$field]=[];
                }
                if(!in_array($zhi,$sear_left[$field])){
                    $sear_left[$field][]=$zhi;
                }
            }
        }
        /*排序*/
        $order_sear_left=array();
        $en_order_left=array('Bore_Dia','Outer_Dia','Width');
        $zh_order_left=array('内径','外径','宽度');
        if($default_lang=='en-us'){
            foreach ($en_order_left as $key => $value) {
               if(isset($sear_left[$value])){
                  $order_sear_left[$value]=$sear_left[$value];
               }
            }
            foreach ($sear_left as $key => $value) {
                $order_sear_left[$key]=$value;
            }
        }
        if($default_lang=='zh-cn'){
            foreach ($zh_order_left as $key => $value) {
               if(isset($sear_left[$value])){
                  $order_sear_left[$value]=$sear_left[$value];
               }
            }
            foreach ($sear_left as $key => $value) {
                $order_sear_left[$key]=$value;
            }
        }
        
        $data['tuijian_part_number_search']=$tuijian_part_number_search;
        $data['sear_left']=$order_sear_left;
        $data['ci']=$sear;
        $data['get']=$get;
        $data['maxclass']=$maxclass;
        //dump($part_number_sear);exit;
        return $data;

    }

    public function class_page_es(Request $request){
        $data['base_data']=$this->base_data;
        $get=request()->get();
        $default_lang=config('app.default_lang');
        $sear=$this->replace_fh(strtolower($get['q']));

        if($default_lang=='en-us'){
            $data['seo_title']=$sear." catalogue Bearing Price & Size Chart | Lily Bearing";
            $data['seo_keywords']=$sear." catalogue bearing, ".$sear." catalogue bearing size, ".$sear." catalogue bearing price, ".$sear." catalogue bearing manufacture, ".$sear." catalogue bearing supplier, Lily Bearing";
            $data['seo_desc']="Lily bearing is bearing manufacture and supplier from china.We supply ".$sear." catalogue bearing with any size and great price. Our bearing could be used including but not limited in medical, automotive, food and other industries. Also a formed pre-sales/sales/after-sales program system were used to meet the actual needs.";
        }else{
            $data['seo_title']=$sear."目录轴承价格和尺寸表 | 养贞轴承";
            $data['seo_keywords']=$sear."目录轴承, ".$sear."目录轴承尺寸, ".$sear."目录轴承价格, ".$sear."目录轴承制造商, ".$sear."目录轴承供应商, 养贞轴承";
            $data['seo_desc']="养贞轴承是中国的轴承制造商和供应商。我们提供".$sear."目录轴承，尺寸和价格均可。我们的轴承可用于包括但不限于医疗、汽车、食品和其他行业。此外，还使用了一套完善的售前/销售/售后计划系统来满足实际需求。";
        }
        $data['appect']=$this->catalogue_search_result($sear);
        $this->assign($data);
        $isMobile=isMobile();
        if($isMobile==1){
            return $this->fetch('class_page_es_phone');
        }else{
            return $this->fetch('class_page_es');
        }
        
    }

    public function catalogue_search_result($sear){
        $default_lang=config('app.default_lang');

        $Esadmin = controller('index/Esadmin');
        $part_number_search=$Esadmin->part_number_search($sear);
        $class_search=$Esadmin->class_search($sear);
        $weidu_search=$Esadmin->weidu_search($sear);

        /*合并两个搜索*/
        $part_number_sear=array_merge($part_number_search,$class_search,$weidu_search);
        $zonghe=array();
        $return_data=array();

        foreach ($part_number_sear as $key => $value) {
            if(!empty($value)){

                foreach ($value as $key1 => $value1) {

                    if($default_lang=='en-us'){
                        $tag=$value1['_source']['Tag_url'];
                    }else{
                        $tag=$value1['_source']['Tag_zh_url'];
                    }
                    if(!in_array($value1['_source']['Part_Number'],$zonghe)){
                        $zonghe[]=$value1['_source']['Part_Number'];

                        $maxclass=json_decode(base64_decode($value1['_source']['maxclass']),true);
                        $tag=json_decode(base64_decode($tag),true);
                        array_shift($tag);
                        $tag_v=reset($tag);
                        $tag_k=key($tag);
                        $max_name=$maxclass['cname'];
                        $max_img=$maxclass['img'];
                        $max_url=$maxclass['url'];
                        if(!isset($return_data[$max_name])){
                            $max_data=array();
                            $return_data[$max_name]['img']=$max_img;
                            $return_data[$max_name]['url']=$max_url;
                            $max_data['name']=$tag_k;
                            $max_data['url']=$tag_v;
                            $max_img=Db::table('lily_classify')->field('img')->where('cname','=',$tag_k)->find();
                            $max_data['img']=$max_img['img'];
                            $return_data[$max_name]['data'][$tag_k]=$max_data;
                        }else{
                            $max_data=array();
                            $max_data['name']=$tag_k;
                            $max_data['url']=$tag_v;
                            $max_img=Db::table('lily_classify')->field('img')->where('cname','=',$tag_k)->find();
                            $max_data['img']=$max_img['img'];
                            if(!isset($return_data[$max_name]['data'][$tag_k])){
                               $return_data[$max_name]['data'][$tag_k]=$max_data;
                            }
                        }
                    }
                    
                }
            }
        }
        $data['return_data']=$return_data;
        $data['ci']=$sear;
        return $data;

    }

    public function qianzhui(Request $request){
        $get=request()->post();
        $Esadmin = controller('index/Esadmin');
        $qianzhui=$Esadmin->qianzhui1($get['q']);
       
        foreach ($qianzhui['jin_data'] as $key => $value) {
            $content='';
            $content_zh='';
            foreach ($value['_source']['Content'] as $k => $v) {
                $a=explode(' || ', $v);
                $content.=$a[0].": ".$a[1].", ";
            }
            foreach ($value['_source']['Content_zh'] as $k => $v) {
                $a=explode(' || ', $v);
                $content_zh.=$a[0].": ".$a[1].", ";
            }
            $qianzhui['jin_data'][$key]['_source']['Content']=rtrim($content,', ');
            $qianzhui['jin_data'][$key]['_source']['Content_zh']=rtrim($content_zh,', ');
        }
        return $qianzhui;
    }

    public function qianzhui1(Request $request){
        $get=request()->post();
        $Esadmin = controller('index/Esadmin');
        $sear=$this->replace_fh(strtolower($get['q']));
        $qianzhui=$Esadmin->qianzhui($sear,10);
        //dump($qianzhui);

        $default_lang=config('app.default_lang');
        
        $return_arr=array();
        $i=0;
        if(!empty($qianzhui['jin_data'])){
            foreach ($qianzhui['jin_data'] as $key => $value) {
                //$return_arr[$value['_source']['Part_Number']]=$value['_source']['url'];
                $return_arr[$i]['p']=$value['_source']['Part_Number'];
                $return_arr[$i]['u']=$value['_source']['url'];
                $i++;
            }
        }
        
        if(!empty($qianzhui['class'])){
            foreach ($qianzhui['class'] as $key => $value) {
                if($default_lang=='en-us'){
                    $Tag_url=json_decode(base64_decode($value['_source']['Tag_url']),true);
                    foreach ($Tag_url as $k => $v) {
                        similar_text(strtolower($k),$sear,$percent);
                        if(strpos(strtolower($k),$sear) !== false||$percent>80){ 
                          if(!isset($return_arr[$k])){
                            //$return_arr[$k]=$v;
                            $return_arr[$i]['p']=$k;
                            $return_arr[$i]['u']=$v;
                            $i++;
                          }
                        }
                    }
                }
                if($default_lang=='zh-cn'){
                    $Tag_url=json_decode(base64_decode($value['_source']['Tag_zh_url']),true);
                    foreach ($Tag_url as $k => $v) {
                        similar_text(strtolower($k),$sear,$percent);
                        if(strpos(strtolower($k),$sear) !== false||$percent>80){ 
                          if(!isset($return_arr[$k])){
                            //$return_arr[$k]=$v;
                            $return_arr[$i]['p']=$k;
                            $return_arr[$i]['u']=$v;
                            $i++;
                          }
                        }
                    }
                } 
            }
        }

        if(!empty($qianzhui['weidu'])){
            foreach ($qianzhui['weidu'] as $key => $value) {
                if($default_lang=='en-us'){
                    $Content=$value['_source']['Content'];
                    foreach ($Content as $k => $v) {
                        similar_text(strtolower($v),$sear,$percent);
                        if(strpos(strtolower($v),$sear) !== false||$percent>80){ 
                          $ek=explode(' || ',$v);

                          if($ek[0]!='Part_arr'){
                              if(!isset($return_arr[str_replace('||',':',$v)])){
                                //$return_arr[str_replace('||',':',$v)]='/sr/?q='.$ek[0]." ".$ek[1];
                                $return_arr[$i]['p']=str_replace('||',':',$v);
                                $return_arr[$i]['u']='/sr/?q='.$ek[0]." ".$ek[1];
                                $i++;
                              }
                          }
                        }
                    }
                }
                if($default_lang=='zh-cn'){
                    $Content=$value['_source']['Content_zh'];
                    foreach ($Content as $k => $v) {
                        similar_text(strtolower($v),$sear,$percent);
                        if(strpos(strtolower($v),$sear) !== false||$percent>80){ 
                          $ek=explode(' || ',$v);
                          if($ek[0]!='Part_arr'){
                              if(!isset($return_arr[str_replace('||',':',$v)])){
                                //$return_arr[str_replace('||',':',$v)]='/sr/?q='.$ek[0]." ".$ek[1];
                                $return_arr[$i]['p']=str_replace('||',':',$v);
                                $return_arr[$i]['u']='/sr/?q='.$ek[0]." ".$ek[1];
                                $i++;
                              }
                          }
                        }
                    }
                } 
            }
        }

        
        
        $tuijian_part_number_search=$this->qianzhui_hou($sear);


      
        $data['left']=$return_arr;
        //dump($return_arr);
        $data['right']=$tuijian_part_number_search;
        $data['firsturl']=reset($return_arr);
        $data['first']=key($return_arr);
       

        return $data;
    }
    
    public function qianzhui_hou1(Request $request){
        $get=request()->post();
        return $this->qianzhui_hou($get['q']);
    }
    public function qianzhui_hou($p){

        $Esadmin = controller('index/Esadmin');
        $sear=$this->replace_fh(strtolower($p));
        $qianzhui=$Esadmin->qianzhui($p,4);
       
        $default_lang=config('app.default_lang');



        $part_number_sear=array_merge($qianzhui['jin_data'],$qianzhui['class'],$qianzhui['weidu']);

        $zonghe=array();
        $return_data=array();
        foreach ($part_number_sear as $key => $value) {
            if(!empty($value)){
                if(!in_array($value['_source']['Part_Number'],$zonghe)){
                    $zonghe[]=$value['_source']['Part_Number'];
                    $return_data[]=$value['_source'];
                }
            }
        }
        $data=array();
      
        foreach ($return_data as $key => $value) {
            $data[$key]['Part_Number']=$value['Part_Number'];
            $data[$key]['brand']=$value['brand'];
            $data[$key]['brand_url']=$value['brand_url'];
            $data[$key]['img']=$value['img'];
            $data[$key]['url']=$value['url'];
            if($default_lang=='en-us'){
                $content='';
                $content1='';
                foreach ($value['Content'] as $k => $v) {
                    $a=explode(' || ', $v);
                    if($a[0]!='Part_arr'&&$a[0]!='Standard Reference'){
                        $content.=$a[0].": ".$a[1].", ";
                    }
                    if($a[0]=='Standard Reference'){
                        $content1='Standard Reference'.": ".$a[1].", ";
                    }
                }
                $data[$key]['Content']=$content1.rtrim($content,', ');
            }
            if($default_lang=='zh-cn'){
                $content='';
                $content1='';
                foreach ($value['Content_zh'] as $k => $v) {
                    $a=explode(' || ', $v);
                    if($a[0]!='Part_arr'&&$a[0]!='Standard Reference'){
                        $content.=$a[0].": ".$a[1].", ";
                    }
                    if($a[0]=='Standard Reference'){
                        $content1='Standard Reference'.": ".$a[1].", ";
                    }
                }
                $data[$key]['Content']=$content1.rtrim($content,', ');
            }
        }
        //dump($data);exit;
        return $data;
    }

}